from django.contrib.admin.widgets import AdminFileWidget
from django.utils.safestring import mark_safe
from django.conf import settings

import Image
import base64

class AdminImageWidget(AdminFileWidget):
    def render(self, name, value, attrs=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)

            file_path = '%s/%s' % (settings.MEDIA_ROOT, file_name)
            try:
                with open(file_path) as img:
                    img_content = img.read()
                    encode_b64 =  base64.b64encode(img_content)
                image = Image.open(file_path)
                image_format = image.format.lower()
                output.append(u' <a href="%s" target="_blank"><img src="data:image/%s;base64,%s"/></a>' % \
                    (image_url, image_format, encode_b64))

            # exception: can not find the file
            except IOError:
                output.append(u' <a href="%s" target="_blank"></a>' % (image_url, ))

        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))
